<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 600px;
      margin: 100px auto;
      border: 1px solid #000;
      box-sizing: border-box;
    }

    .box * {
      box-sizing: border-box;
    }

    .box .header {
      width: 100%;
      height: 50px;
      display: flex;
      border-bottom: 1px solid #222;
    }

    .box .header span {
      transition: all 0.3s;
      background-color: #fff;
      line-height: 50px;
      text-align: center;
      cursor: pointer;
      font-size: 16px;
      border-right: 1px solid #000;
      flex: 1;
    }

    div.header>span:last-child {
      border-right-width: 0;
    }

    .box .header span.active,
    .box .header span:hover {
      background-color: #ccc;
    }

    .box .main {
      width: 100%;
      height: 300px;
      line-height: 300px;
    }

    .box .main div {
      width: 100%;
      text-align: center;
      font-size: 60px;
      font-weight: 800;
      display: none;
    }

    .box .main div.active {
      display: block;
    }
  </style>
</head>

<body>
  <div class="box" id="box1"></div>
  <div class="box" id="box2"></div>

  <script>
    // ============================= 添加点击事件 =============================
    // 获取到tab栏的容器
    let box1 = document.querySelector('#box1')

    // 准备数据
    // 头部导航数据
    let headerArr = ['动物', '明星', '热点', '广场']
    // 内容数据
    let contentArr = ['动物世界', '明星新闻', '热点新闻', '广场趣事']


    // =========================== 这是动态创建节点代码 ===========================
    let headerDiv = document.createElement('div')
    let mainDiv = document.createElement('div')

    headerDiv.classList.add('header')
    mainDiv.classList.add('main')

    box1.appendChild(headerDiv)
    box1.appendChild(mainDiv)

    for (let i = 0; i < headerArr.length; i++) {
      let newSpan = document.createElement('span')
      let newDiv = document.createElement('div')

      newSpan.innerHTML = headerArr[i]
      newDiv.innerHTML = contentArr[i]

      headerDiv.appendChild(newSpan)
      mainDiv.appendChild(newDiv)

      if (i === 0) {
        newSpan.classList.add('active')
        newDiv.classList.add('active')
      }
    }


    // =========================== 添加点击事件代码 ===========================
    let spans = box1.querySelectorAll('.header span')
    let divs = box1.querySelectorAll('.main div')

    for (let i = 0; i < spans.length; i++) {
      spans[i].addEventListener('click', function () {
        // 在获取active的时候，一定要精确获取
        box1.querySelector('.header span.active').classList.remove('active')
        this.classList.add('active')

        // 排他内容div
        box1.querySelector('.main div.active').classList.remove('active')
        divs[i].classList.add('active')
      })
    }
  </script>
</body>

</html>